package org.shiki.hrm.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.sun.xml.internal.bind.v2.TODO;
import org.shiki.hrm.constant.TenantConstant;
import org.shiki.hrm.domain.Employee;
import org.shiki.hrm.domain.LoginUser;
import org.shiki.hrm.domain.Tenant;
import org.shiki.hrm.dto.TenantRegDto;
import org.shiki.hrm.fein.LoginUserFeignClient;
import org.shiki.hrm.mapper.EmployeeMapper;
import org.shiki.hrm.mapper.TenantMapper;
import org.shiki.hrm.query.TenantQuery;
import org.shiki.hrm.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.shiki.hrm.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shiki
 * @since 2022-03-09
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

	@Autowired
	private TenantMapper tenantMapper;

	@Autowired
	private LoginUserFeignClient client;

	@Autowired
	private EmployeeMapper employeeMapper;

	@Override
	public List<Tenant> findTypePage(Page<Tenant> page, TenantQuery query) {
		Page<Tenant> tenantPage = new Page<>(query.getPage(), query.getRows());
		List<Tenant> list = tenantMapper.findTypePage(tenantPage, query);
		return list;
	}

	@Override
	public void entrying(TenantRegDto dto) {
		/*
			TODO  参数校验
		 */
		// 先保存auth中的t_login_user
		LoginUser loginUser = new LoginUser();
		Employee employee = dto.getEmployee();
		loginUser.setUsername(employee.getUsername());
		loginUser.setPassword(employee.getPassword());
		loginUser.setMealId(dto.getMealId());
		AjaxResult result = client.entrying(loginUser);
		// 判断auth是否保存成功
		if (result.isSuccess()){
			// 再保存t_employee
			// 获取保存t_login_user返回的主键
			Integer loginId = (Integer) result.getResultObj();
			// 返回的主键转化为Long类型再保存
			employee.setLoginId(Long.valueOf(loginId));
			Date date = new Date();
			employee.setInputTime(date);
			employee.setState(TenantConstant.EMP_STATE_NORMAL);
			employee.setType(TenantConstant.EMP_TYPE_TENANT_ADMIN);
			employeeMapper.insert(employee);
			// 再保存t_tenant
			Tenant tenant = dto.getTenant();
			tenant.setAdminId(employee.getId());
			tenant.setRegisterTime(date);
			tenant.setState(TenantConstant.TENANT_CHECK_WAIT);
			tenantMapper.insert(tenant);
		}
	}
}
